package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	// 1. 从 name.txt 读取日志文件名
	logFileName, err := getLogFileNameFromTxt("name.xml")
	if err != nil {
		fmt.Printf("Error reading name.txt: %v\n", err)
		return
	}

	// 2. 创建输出文件名
	outputFileName := logFileName + "_orderid.txt"

	// 3. 打开日志文件并解析，结果写入输出文件
	err = parseLogFile(logFileName, outputFileName)
	if err != nil {
		fmt.Printf("Error parsing log file: %v\n", err)
		return
	}

	fmt.Printf("Successfully wrote results to %s\n", outputFileName)
}

// 从 name.txt 读取日志文件名
func getLogFileNameFromTxt(txtFile string) (string, error) {
	file, err := os.Open(txtFile)
	if err != nil {
		return "", fmt.Errorf("failed to open %s: %v", txtFile, err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	if scanner.Scan() {
		logFileName := strings.TrimSpace(scanner.Text())
		if logFileName == "" {
			return "", fmt.Errorf("log filename is empty in %s", txtFile)
		}
		return logFileName, nil
	}

	if err := scanner.Err(); err != nil {
		return "", fmt.Errorf("error reading %s: %v", txtFile, err)
	}

	return "", fmt.Errorf("no log filename found in %s", txtFile)
}

// 解析日志文件并提取时间和订单ID，结果写入输出文件
func parseLogFile(logFile, outputFile string) error {
	// 打开日志文件
	inFile, err := os.Open(logFile)
	if err != nil {
		return fmt.Errorf("error opening log file: %v", err)
	}
	defer inFile.Close()

	// 创建输出文件
	outFile, err := os.Create(outputFile)
	if err != nil {
		return fmt.Errorf("error creating output file: %v", err)
	}
	defer outFile.Close()

	writer := bufio.NewWriter(outFile)
	defer writer.Flush()

	scanner := bufio.NewScanner(inFile)
	for scanner.Scan() {
		line := scanner.Text()
		if line == "" {
			continue
		}

		// 提取时间部分 (YYYYMMDD-HH:MM:SS.sss)
		timeEnd := 21 // 时间戳固定21个字符
		if len(line) < timeEnd {
			continue
		}
		timestamp := line[:timeEnd]

		// 查找FIX消息开始位置
		msgStart := strings.Index(line, "8=FIXT.1.1")
		if msgStart == -1 {
			continue
		}
		fixMsg := line[msgStart:]

		// 提取订单ID (11=后面的值)
		idStart := strings.Index(fixMsg, "11=")
		if idStart == -1 {
			continue
		}

		// 查找订单ID结束位置 (SOH字符或行尾)
		idValue := fixMsg[idStart+3:]
		endPos := strings.IndexAny(idValue, "\x01 ")
		if endPos == -1 {
			endPos = len(idValue)
		}
		orderID := idValue[:endPos]

		// 写入结果到输出文件
		_, err := writer.WriteString(fmt.Sprintf("%s %s\n", timestamp, orderID))
		if err != nil {
			return fmt.Errorf("error writing to output file: %v", err)
		}
	}

	if err := scanner.Err(); err != nil {
		return fmt.Errorf("error reading log file: %v", err)
	}

	return nil
}
